<?php 
namespace app\models;

use app\models\MoneyRecord;
use think\Model;

use app\models\UserTree;


class User extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $updateTime = 'updated';
    protected $insert = ['invite_code'];

    protected function setInviteCodeAttr()
    {
        $lastId = $this->order('id', 'desc')->field('id')->value('id');
        $id = rand() . $lastId;
        $str = 'GFCDRL97XP8J1KYQW643M2EUASTB5HZN';
        $code = '';
        for ($i = 0; $i < strlen($id); $i++) {
            $code .= $str[$id[$i]];
        }
        return $code;
    }

    public function setPasswordAttr($value)
    {
        return md5(md5($value));
    }

    public function setTokenAttr($value)
    {
        return md5($value);
    }

    public function setMobileAttr($value)
    {
        if (empty($value)) {
            return uniqid();
        } else {
            return $value;
        }
    }

    public function getLevelNameAttr($value, $data)
    {
        if (isset($data['level'])) {
            $lang = isset(request()->header()['language']) ? request()->header()['language'] : '';
            if ($lang == 'en-us') {
                return config('base.level')[$data['level']]['us'];
            }
            return config('base.level')[$data['level']]['name'];
        }
    }

    public function getChildsAttr()
    {
        return $this->where('parent_id', $this->id)->count();
    }

    public function getChildAttr($value, $data)
    {
        return [
            'child' => $this->where('parent_id', $data['id'])->count(),
            'team' => count(array_filter(explode(',', $value))),
            'teams' => array_filter(explode(',', $value))
        ];
    }

    public function register($data)
    {
        $this->save($data);
        $voucher_usdt=$data["voucher_usdt"];
        if($voucher_usdt!=0){
            (new MoneyRecord)->registerLog($this->id,$voucher_usdt);
        }
        return $this;
    }

    public function getTeamsAttr($value, $data)
    {
        return UserTree::where('uid', $data['id'])->find();
    }

    public function getMoneyAttr($value)
    {

        return getValueByDo($value,8);
    }

    public function getForzeMoneyAttr($value)
    {
        return getValueByDo($value,8);

    }

    public function getVoucherUsdtAttr($value)
    {

        return getValueByDo($value,8);
    }

    public function getCommissionUsdtAttr($value)
    {
        return getValueByDo($value,8);
    }
    public function getWinUsdtAttr($value)
    {
        return getValueByDo($value,8);
    }


}
